<template>
  <div class="add-second-wrap">
    <step />
    <!-- <el-row class="item-container">
      <div class="title">随时退：</div>
      <el-select v-model="info.able_return" placeholder="请选择">
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.value"
          :value="item.value"
        />
      </el-select>
    </el-row> -->
    <el-row class="item-container">
      <div class="title-time">
        <svg-icon icon-class="required" class-name="custom-class" />
        <div class="title">有效时间：</div>
      </div>
      <el-date-picker v-model="info.date" type="daterange" style="width: 420px" value-format="yyyy-MM-dd" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" />
    </el-row>
    <el-row class="item-container">
      <div class="title-wrap">
        <div class="title ex">适用范围：</div>
        <el-button type="primary" class="btn" @click="handleAddBag">新增</el-button>
      </div>
    </el-row>
    <el-row class="item-container item-container-other">
      <div v-for="(item, index) of info.balcony" :key="index" style="margin-bottom: 10px" class="item-left">
        <div class="title">名称：</div>
        <el-input v-model="item.name" type="text" style="width: 200px" placeholder="请输入名称" class="input-container" />
        <div class="title title-right">人数：</div>
        <el-input v-model="item.sug_people_num" type="text" style="width: 200px" placeholder="请输入内容" class="input-container" />
        <div class="title title-right">数量：</div>
        <el-input v-model="item.quantity" type="text" style="width: 200px" placeholder="请输入内容" class="input-container" />
        <el-button type="primary" style="margin-left: 20px" @click="handleDeleteBag(index)">删除</el-button>
      </div>
    </el-row>
    <el-row class="item-container">
      <div class="title-wrap">
        <div class="title">套餐内容：</div>
        <el-button type="primary" class="btn" @click="handleAddTab">新增</el-button>
        <div style="margin-left: 10px;fone-size:12px; line-height:36px">（点击表格会增加一行）</div>
      </div>
    </el-row>
    <el-row class="item-container item-container-other">
      <div v-for="(item, index) of info.item" :key="index" style="width: 100%;margin-bottom:20px">
        <div class="drink">
          <div class="title">分类：</div>
          <el-input v-model="item.package_cate_name" type="text" style="width: 200px" placeholder="请输入名称" class="input-container" />
        </div>
        <el-table ref="multipleTable" :data="item.goods" border tooltip-effect="dark" style="width: 80%">
          <el-table-column prop="name" label="名称" min-width="200" class="cursor">
            <template slot-scope="scope">
              <template v-if="scope.row.edit">
                <el-input v-model="scope.row.name" style="margin-right:10px;width: 100px;" class="edit-input" size="small" />
                <el-button class="cancel-btn" size="small" icon="el-icon-refresh" type="warning" @click="cancelEdit(scope)">取消</el-button>
              </template>
              <div v-else class="tab-content" @dblclick="scope.row.edit=true" @click="handleAddTabItem(scope, index)">{{ scope.row.name }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="num" label="数量" min-width="200" class="cursor">
            <template slot-scope="scope">
              <template v-if="scope.row.edit">
                <el-input v-model="scope.row.num" style="margin-right:10px;width: 100px;" class="edit-input" size="small" />
                <el-button class="cancel-btn" size="small" icon="el-icon-refresh" type="warning" @click="cancelEdit(scope)">取消</el-button>
              </template>
              <div v-else class="tab-content" @dblclick="scope.row.edit=true" @click="handleAddTabItem(scope, index)">{{ scope.row.num }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="price" label="价钱" min-width="200" class="cursor">
            <template slot-scope="scope">
              <template v-if="scope.row.edit">
                <el-input v-model="scope.row.price" style="margin-right:10px;width: 100px;" class="edit-input" size="small" />
                <el-button class="cancel-btn" size="small" icon="el-icon-refresh" type="warning" @click="cancelEdit(scope)">取消</el-button>
              </template>
              <div v-else class="tab-content" @dblclick="scope.row.edit=true" @click="handleAddTabItem(scope, index)">{{ scope.row.price }}</div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template slot-scope="scope">
              <el-button v-if="scope.row.edit" type="success" icon="el-icon-circle-check-outline" class="operation-btn" @click="confirmEdit(scope)">确认</el-button>
              <el-button v-else type="primary" icon="el-icon-edit" class="operation-btn" @click="scope.row.edit=!scope.row.edit">编辑</el-button>
              <el-button type="primary" class="operation-btn" @click="handleDeleteTab(scope, index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-row>
    <el-row class="item-container">
      <div class="title">时段：</div>
      <el-time-select v-model="startTime" :editable="false" placeholder="起始时间" :picker-options="{ start: '00:00', step: '00:30', end: '23:30'}" />
      <el-time-select v-model="endTime" :editable="false" style="margin-left: 10px" placeholder="结束时间" :picker-options="{ start: '00:00', step: '00:30', end: '23:30'}" />
      <el-button type="primary" style="margin-left: 10px" class="btn" @click="handleAddTimer">新增</el-button>
      <el-button type="primary" style="margin-left: 10px" class="btn" @click="handleDeleteTimer">删除</el-button>
    </el-row>
    <el-row class="item-container timer">
      <div v-for="(item, index) of info.time_solt" :key="index" class="timer-item">
        <el-checkbox v-model="item.check" :label="item.name" border />
      </div>
    </el-row>
    <el-row class="item-container">
      <div class="title">使用规则：</div>
      <el-input v-model="info.use_rule" type="textarea" placeholder="请输入简介" class="textarea-container" />
    </el-row>
    <el-row class="item-container">
      <div class="title">预定说明：</div>
      <el-input v-model="info.refund_rule" type="textarea" placeholder="请输入简介" class="textarea-container" />
    </el-row>
    <el-row class="item-container right">
      <el-button type="primary" class="add-btn" @click="handleSubmit">完成</el-button>
    </el-row>
  </div>
</template>
<script>
import Step from '@/components/step'
import { addHotel, editType } from '@/api/combo'
import { deepClone } from '@/utils/index.js'
export default {
  name: 'KtvSecond',
  components: {
    Step
  },
  data() {
    return {
      info: {
        able_return: '支持',
        date: '',
        balcony: [{ name: '', sug_people_num: '', quantity: '' }],
        item: [{ package_cate_name: '', goods: [{ name: '', num: '', price: '', edit: false }] }],
        use_rule: '',
        refund_rule: '',
        start_date: '',
        end_date: '',
        time_solt: []
      },
      options: [
        {
          label: '0',
          value: '不支持'
        },
        {
          label: '1',
          value: '支持'
        }
      ],
      startTime: '',
      endTime: ''
    }
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      const info = JSON.parse(this.$route.query.info)
      if (!info) {
        this.$router.push('/merchandise/combo/ktv')
      } else {
        if (!Array.isArray(info.package_pics)) {
          info.package_pics = [info.package_pics]
        }
        if (info.id) {
          info.able_return = Number(info.able_return) === 1 ? '支持' : '不支持'
          info.date = info.start_date.length ? [info.start_date, info.end_date] : ''
          info.balcony = info.balcony ? (info.item.length === 0 ? [{ name: '', sug_people_num: '', quantity: '' }] : this.jsonBalcony(info.balcony)) : [{ name: '', sug_people_num: '', quantity: '' }]
          info.item = info.item ? (info.item.length === 0 ? [{ package_cate_name: '', goods: [{ name: '', num: '', price: '', edit: false }] }] : this.jsonGoods(info.item)) : [{ package_cate_name: '', goods: [{ name: '', num: '', price: '', edit: false }] }]
          info.time_solt = this.initTimeSolt(info.time_solt)
          this.info = info
        } else {
          this.info = Object.assign({}, this.info, { ...info })
        }
      }
    },
    // 初始化时段
    initTimeSolt(array) {
      if (!Array.isArray(array)) {
        array = JSON.parse(array)
      }
      const result = []
      array.map((item) => {
        result.push({ name: item, check: true })
      })
      return result
    },
    // 序列化表格
    jsonGoods(array) {
      return array.map((item) => {
        item = typeof item === 'string' ? JSON.parse(item) : item
        item.goods = Array.isArray(item.goods) ? item.goods : JSON.parse(item.goods)
        item.goods.map((subitem) => {
          subitem = Object.assign({}, subitem, { edit: false })
          return subitem
        })
        return item
      })
    },
    // 序列化包厢
    jsonBalcony(array) {
      return array.map((item) => {
        item = typeof item === 'string' ? JSON.parse(item) : item
        return item
      })
    },
    // 新增包厢
    handleAddBag() {
      this.info.balcony.push({ name: '', sug_people_num: '', quantity: '' })
    },
    // 删除包厢
    handleDeleteBag(index) {
      this.info.balcony.splice(index, 1)
    },
    // 新增酒水
    handleAddTab() {
      this.info.item.push({ package_cate_name: '', goods: [{ name: '', num: '', price: '', edit: false }] })
    },
    // 删除表格
    handleDeleteTab(scope, index) {
      const len = this.info.item[index].goods.length
      if (len === 1) {
        this.info.item.splice(index, 1)
      } else {
        this.info.item[index].goods.splice(scope.$index, 1)
      }
    },
    // 编辑表格
    cancelEdit(scope) {
      scope.row.edit = false
    },
    // 确认
    confirmEdit(scope) {
      scope.row.edit = false
    },
    // 增加表格
    handleAddTabItem(scope, index) {
      console.log(this.info.item[index].goods)
      this.info.item[index].goods.push({ name: '', num: '', price: '', edit: false })
    },
    // 增加时段
    handleAddTimer() {
      const { startTime, endTime } = this
      if (startTime.trim() === '' || endTime.trim() === '') {
        this.$message.warning({
          message: '开始时间段或者结束时间段不能为空',
          duration: 1000
        })
        return
      } else {
        this.info.time_solt.push({ name: `${startTime}-${endTime}`, check: true })
        this.startTime = ''
        this.endTime = ''
      }
    },
    // 删除时段
    handleDeleteTimer() {
      const time = this.info.time_solt
      for (let index = time.length - 1; index >= 0; index--) {
        if (time[index].check) {
          time.splice(index, 1)
        }
      }
    },
    // 提交
    handleSubmit() {
      this.validity()
    },
    // 改变上传格式
    validity() {
      const info = deepClone(this.info)
      info.package_id = info.id || 0
      info.able_return = info.able_return === '支持' ? 1 : 0
      info.start_date = this.validityDate(info.date)
      info.end_date = this.validityDate(info.date, 1)
      info.package_pics = this.validityPics(info.package_pics)
      info.balcony = this.validityBag(info.balcony)
      if (!info.balcony) return
      info.item = this.validityItem(info.item)
      console.log(info.item)
      info.time_solt = JSON.stringify(this.validityTimeSolt(info.time_solt))
      if (!info.start_date || !info.end_date) { return }
      info.id ? this.edit(info) : this.add(info)
    },
    // // 深拷贝对象
    // deepCopy(obj) {
    //   const objClone = Array.isArray(obj) ? [] : {}
    //   if (obj && typeof obj === 'object') {
    //     for (const key in obj) {
    //       if (obj[key] && typeof obj[key] === 'object') {
    //         objClone[key] = this.deepCopy(obj[key])
    //       } else {
    //         objClone[key] = obj[key]
    //       }
    //     }
    //   }
    //   return objClone
    // },
    // 改变包厢格式
    validityBag(array) {
      for (let index = array.length - 1; index >= 0; index--) {
        if (Number(array[index].quantity) > 100 && isNaN(parseInt(array[index].quantity))) {
          this.$message.warning({
            message: `包厢第${index + 1}个数量应该是数字且小于100`,
            duration: 2000
          })
          break
        }
        if (array[index].name.trim() === '' || array[index].sug_people_num.toString().trim() === '' || array[index].quantity.toString().trim() === '') {
          array.splice(index, 1)
        }
      }
      array = array.length ? array : []
      return array
    },
    // 改变酒水格式
    validityItem(array) {
      for (let index = array.length - 1; index >= 0; index--) {
        if (array[index].package_cate_name.trim() === '') {
          array.splice(index, 1)
        } else {
          for (let j = array[index].goods.length - 1; j >= 0; j--) {
            delete array[index].goods[j].edit
            if (array[index].goods[j].name.trim() === '' || array[index].goods[j].price.toString().trim() === '' || array[index].goods[j].num.toString().trim() === '') {
              array[index].goods.splice(j, 1)
            }
          }
        }
      }
      array = array.length ? array : []
      return array
    },
    // 改变有效时间，结束时间
    validityDate(array, num = 0) {
      if (!Array.isArray(array)) {
        this.$message.warning({
          message: '有效时间不能为空',
          duration: 1000
        })
        return false
      } else {
        return array[num]
      }
    },
    // 改变时段格式
    validityTimeSolt(array) {
      const result = []
      array.map((item) => {
        result.push(item.name)
      })
      return result
    },
    // 改变轮播图
    validityPics(array) {
      return array.join('|')
    },
    // 编辑
    async edit(info) {
      await editType({ ...info })
      this.$message.success({
        message: '编辑成功',
        duration: 1000
      })
      this.$router.push({
        path: '/merchandise/combo/ktv'
      })
    },
    // 添加
    async add(info) {
      console.log(info)
      await addHotel({ ...info })
      this.$message.success({
        message: '添加成功',
        duration: 1000
      })
      this.$router.push({
        path: '/merchandise/combo/ktv'
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.add-second-wrap {
  width: 100%;
  background-color: #fff;
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  right: 0;
  z-index: 10;
  padding: 20px;
  box-sizing: border-box;
  overflow-y: scroll;
  overflow-x: hidden;
  .item-container{
    width: 100%;
    display: flex;
    align-items: center;
    margin-bottom: 15px;
    .title-time{
      display: flex;
      width: 100px;
      position: relative;
      .custom-class{
        width: 10px;
        height: 10px;
        position: absolute;
        top: 50%;
        transform: translateY(-50%);
        left: -15px;
      }
    }
    .title{
      font-size: 14px;
      line-height: 30px;
      width: 100px;
    }
    .ex {
      position: relative;
      &::before {
        content: '（如：包厢）';
        position: absolute;
        left: -6px;
        bottom: -15px;
        color: #757575;
        font-size: 12px;
      }
    }
    .title-right{
      margin-left: 40px;
    }
    .management-btn{
      margin-left: 15px;
    }
    .input-container{
      width: 400px;
    }
    .textarea-container{
      width: 40%;
    }
    .window {
      display: flex;
      align-items: center;
      margin-left: 40px;
    }
    .item-left,.item-right{
      display: flex;
      align-items: center;
      p {
        margin-left: 10px;
      }
    }
    .add-btn {
      width: 200px;
    }
  }
  .right{
    justify-content: flex-end;
  }
  .title-wrap{
    width: 100%;
    display: flex;
  }
  .item-container-other {
    padding-left: 100px;
    flex-direction: column;
    justify-content: flex-start;
    align-items: flex-start;
    box-sizing: border-box;
  }
  .drink{
    width: 100%;
    display: flex;
    margin-bottom: 10px;
  }
  .timer {
    margin-left: 100px;
    flex-wrap: wrap;
    .timer-item {
      margin-bottom: 10px;
      margin-right: 20px;
    }
  }
  .cursor {
    cursor: pointer;
  }
  .tab-content{
    width: 100%;
    height: 30px;
    line-height: 30px;
  }
  .operation-btn{
    margin-bottom: 10px;
  }
}
</style>
